<?php

//安装依赖包
//最低SDK版本要求：viapi20230117的SDK版本需大于等于1.0.0。
//可以在此仓库地址中引用最新版本SDK：https://packagist.org/packages/alibabacloud/viapi-20230117
//composer require alibabacloud/viapi-20230117
namespace App\Common;

use AlibabaCloud\SDK\Viapi\V20230117\Viapi;
use \Exception;
use AlibabaCloud\Tea\Utils\Utils;
use Darabonba\OpenApi\Models\Config;
use AlibabaCloud\SDK\Viapi\V20230117\Models\GetAsyncJobResultRequest;
use AlibabaCloud\Tea\Utils\Utils\RuntimeOptions;

class GetAsyncJobResult
{

    /**
     * 使用AK&SK初始化账号Client
     * @param string $accessKeyId
     * @param string $accessKeySecret
     * @return Viapi Client
     */
    public static function createClient($accessKeyId, $accessKeySecret)
    {
        //初始化配置对象Darabonba\OpenApi\Models\Config。
        //Config对象存放accessKeyId、accessKeySecret、endpoint等配置
        $config = new Config([
            "accessKeyId" => $accessKeyId,
            "accessKeySecret" => $accessKeySecret
        ]);
        // 访问的域名
        $config->endpoint = "viapi.cn-shanghai.aliyuncs.com";
        return new Viapi($config);
    }

    /**
     * @param $args
     * @return false|mixed
     */
    public static function main($args)
    {
        // 创建AccessKey ID和AccessKey Secret，请参考https://help.aliyun.com/document_detail/175144.html
        // 如果您使用的是RAM用户的AccessKey，还需要为子账号授予权限AliyunVIAPIFullAccess，请参考https://help.aliyun.com/document_detail/145025.html
        // 从环境变量读取配置的AccessKey ID和AccessKey Secret。运行代码示例前必须先配置环境变量。
        $accessKeyId = 'LTAI5tEW76t7hqHbyADZeQW2';
        $accessKeySecret = '6uTK0HlMdikxy7o9hNkckCEwnOjX92';
        $client = self::createClient($accessKeyId, $accessKeySecret);
        $getAsyncJobResultRequest = new GetAsyncJobResultRequest([
            "jobId" => $args['jobId']
        ]);
        $runtime = new RuntimeOptions([]);
        try {
            $resp = $client->getAsyncJobResultWithOptions($getAsyncJobResultRequest, $runtime);
            # 获取整体结果
            $data = json_decode(Utils::toJSONString($resp->body), true);
            if ($data['Data']['Result']) {
                $result = json_decode($data['Data']['Result'], true);
                if ($result['resultUrl'] && isset($result['resultUrl'])) {
                    return $result['resultUrl'];
                }
                return false;
            }
            return false;
        } catch (Exception $exception) {
            return false;
        }
    }
}
